package com.android.advertising;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.MenuItemCompat.OnActionExpandListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gcm.GCMRegistrar;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class MainActivity extends ActionBarActivity implements
		SearchView.OnQueryTextListener, SearchView.OnCloseListener {
	private static final String TAG = "MainActivity";
	private PullToRefreshListView mPullRefreshListView;
	private ArticleDatabase database;
	private ArticleAdapter adapter;
	//List of articles
	private ArrayList<Article> listArticles;
	private List<Article> drawingArticles;
	ActionBar actionBar;
	private static final int LIST_SIZE = 5;
	private static final int LIST_MORE = 5;
	ListView actualListView;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_main);
		// start service
		if (!MainService.isReady()) {
			Intent intent = new Intent(this, MainService.class);
			startService(intent);
		} else {
			MainService.getInstance().removeNotification();
		}
		actionBar = getSupportActionBar();
		actionBar.setDisplayUseLogoEnabled(true);
		setSupportProgressBarIndeterminateVisibility(false);
		// /
		mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.listView);
		mPullRefreshListView.setMode(Mode.PULL_FROM_END);
		actualListView = mPullRefreshListView.getRefreshableView();
		// Set a listener to be invoked when the list should be refreshed.
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						String label = DateUtils.formatDateTime(
								getApplicationContext(),
								System.currentTimeMillis(),
								DateUtils.FORMAT_SHOW_TIME
										| DateUtils.FORMAT_SHOW_DATE
										| DateUtils.FORMAT_ABBREV_ALL);

						// Update the LastUpdatedLabel
						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);
						// customLoadMoreDataFromApi(drawingArticles.size() -
						// 1);
						// Do work to refresh the list here.
						new GetDataTask().execute(""
								+ (drawingArticles.size() - 1));
					}
				});

		database =  ArticleDatabase.getInstance(getApplicationContext());
		listArticles = database.getAllRecords();
		// drawingArticles = new List<Article>();
		if (listArticles.size() >= LIST_SIZE) {
			drawingArticles = listArticles.subList(0, LIST_SIZE);
		}else {
			drawingArticles = listArticles.subList(0, listArticles.size());
		}
		adapter = new ArticleAdapter(getApplicationContext(), drawingArticles);
		actualListView.setAdapter(adapter);
		if (drawingArticles.size() > 1) {
			actualListView.setSelection(drawingArticles.size() - 1);
		}
		actualListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				Log.i(TAG, "position = " + position);
				long id = drawingArticles.get(position - 1).getId();
				drawingArticles.get(position - 1).setIsRead(1);
				Intent i = new Intent(getApplicationContext(),
						ArticleDetailActivity.class);
				i.putExtra(Constants.ARTICLES_ID, id);
				startActivity(i);
			}
		});
		if (listArticles.size() == 0) {
			loadMoreArticlesFromServer(getApplicationContext());
		}
		new GCMRegisterAsync().execute(getApplicationContext());

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);

		MenuItem searchItem = menu.findItem(R.id.action_search);
		SearchView searchView = (SearchView) MenuItemCompat
				.getActionView(searchItem);
		searchView.setOnQueryTextListener(this);
		searchView.setOnCloseListener(this);

		MenuItemCompat.setOnActionExpandListener(searchItem,
				new OnActionExpandListener() {
					@Override
					public boolean onMenuItemActionCollapse(MenuItem item) {
						// Do something when collapsed
						Log.i(TAG, "collapsed");
						adapter.setListArticle(drawingArticles);
						adapter.notifyDataSetChanged();
						if (drawingArticles.size() > 1) {
							actualListView.setSelection(drawingArticles.size() - 1);
						}
						return true; // Return true to collapse action view
					}

					@Override
					public boolean onMenuItemActionExpand(MenuItem item) {
						// Do something when expanded
						return true; // Return true to expand action view
					}
				});

		// Configure the search info and add any event listeners
		return super.onCreateOptionsMenu(menu);
	}

	// Append more data into the adapter
	public void customLoadMoreDataFromApi(int offset) {

		// actualListView.setSelection(1);
	}

	private class GetDataTask extends AsyncTask<String, Void, Void> {

		@Override
		protected Void doInBackground(String... params) {
			// Simulates a background job.
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
			}
			// This method probably sends out a network request and appends new
			// data
			// items to your adapter.
			// Use the offset value and add it as a parameter to your API
			// request to
			// retrieve paginated data.
			// Deserialize API response and then construct new objects to append
			// to
			// the adapter
			int lastIndex;
			int offset = Integer.valueOf(params[0]);
			if (listArticles.size() < offset + LIST_MORE) {
				lastIndex = listArticles.size();
			} else {
				lastIndex = offset + LIST_MORE;
			}
			drawingArticles = listArticles.subList(0, lastIndex);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			adapter.setListArticle(drawingArticles);
			adapter.notifyDataSetChanged();
			// Call onRefreshComplete when the list has been refreshed.
			mPullRefreshListView.onRefreshComplete();
			super.onPostExecute(result);
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.action_refresh) {
			loadMoreArticlesFromServer(getApplicationContext());
		}
		return super.onOptionsItemSelected(item);
	}

	public void onResume() {
		super.onResume();
		adapter.notifyDataSetChanged();
		// if (drawingArticles.size() > 1) {
		// actualListView.setSelection(drawingArticles.size() - 1);
		// }
	}

	private void loadMoreArticlesFromServer(Context ctx) {
		setSupportProgressBarIndeterminateVisibility(true);
		StringRequest postRequest = new StringRequest(Request.Method.GET,
				Constants.REST_SERVER + Constants.REST_ARTICLES,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						// response
						Log.d(TAG, response);
						parsingJSONRespone(response);
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// error
						setSupportProgressBarIndeterminateVisibility(false);
						Log.d(TAG, error.toString());
					}
				}) {
			@Override
			protected Map<String, String> getParams() {
				Map<String, String> params = new HashMap<String, String>();
				params.put("numbers", "" + 50);
				if (listArticles.size() > 1) {
					params.put("lastid",
							"" + listArticles.get(listArticles.size() - 1));
				} else {
					params.put("lastid", "0");
				}
				return params;
			}
		};
		RequestQueue queue = Volley.newRequestQueue(ctx);
		queue.add(postRequest);
	}

	private void parsingJSONRespone(String results) {
		try {
			JSONObject responeJsonObject = new JSONObject(results);
			JSONArray jsonArray = responeJsonObject
					.getJSONArray(Constants.ARTICLES_DATA);
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject item = jsonArray.getJSONObject(i);
				int id = item.getInt(Constants.ARTICLES_SERVER_ID);
				if (!database.findArticleByServerId(id)) {
					String title = item.getString(Constants.ARTICLES_TITLE);
					long time = item.getLong(Constants.ARTICLES_TIME);
					String link = item.getString(Constants.ARTICLES_LINK);
					String thumbLink = item
							.getString(Constants.ARTICLES_THUMBLINK);
					Article article = new Article();
					article.setServerId(id);
					article.setTitle(title);
					article.setCreatedTime(time);
					article.setLink(link);
					article.setThumbLink(thumbLink);
					article.setIsRead(0);
					article.setIsactive(1);
					long recordID = database.createRecord(article);
					article.setId(recordID);
				} else {
					Log.i(TAG, "id " + id + " already exist");
				}
			}
			listArticles = database.getAllRecords();
			if (listArticles.size() >= LIST_SIZE) {
				drawingArticles = listArticles.subList(0, LIST_SIZE);
			}else {
				drawingArticles = listArticles.subList(0, listArticles.size());
			}			adapter.setListArticle(drawingArticles);
			adapter.notifyDataSetChanged();
			if (drawingArticles.size() > 1) {
				actualListView.setSelection(drawingArticles.size() - 1);
			}
			setSupportProgressBarIndeterminateVisibility(false);
		} catch (JSONException e) {
			Log.e(TAG, "error" + e.toString());
		}
		// mPullRefreshListView.onRefreshComplete();
		// mPullRefreshListView.setSelection(1);
	}

	private class GCMRegisterAsync extends AsyncTask<Context, Void, Void> {

		@Override
		protected Void doInBackground(Context... params) {
			Context context = params[0];
			final SharedPreferences prefs = PreferenceManager
					.getDefaultSharedPreferences(context);
			String registrationId = prefs.getString(Constants.GCM_REG_ID, "");
			int flag = prefs.getInt(Constants.GCM_DELIVER_FLAG, 0);
			String regIdSendDate = prefs.getString(Constants.GCM_REG_ID_DATE,
					"");
			SimpleDateFormat spd = new SimpleDateFormat("yyMMdd");
			String today = spd.format(Calendar.getInstance().getTime());
			if (registrationId.length() != 0 && regIdSendDate.equals(today)) {
				Log.i(TAG, "registrationId = " + registrationId);
				// return null; // tam thoi comment de test
			}
			Log.d(TAG, "request to new RegId (registrationId = "
					+ registrationId);
			try {
				GCMRegistrar.register(context, Constants.SENDER_ID); // old
			} catch (Exception e) {
				Log.i(TAG, "" + e.toString());
			}
			return null;
		}
	}

	@Override
	public boolean onQueryTextChange(String arg0) {
		ArrayList<Article> results = searchArticle(listArticles, arg0);
		adapter.setListArticle(results);
		adapter.notifyDataSetChanged();
		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String arg0) {
		ArrayList<Article> results = searchArticle(listArticles, arg0);
		adapter.setListArticle(results);
		adapter.notifyDataSetChanged();
		return false;
	}

	private ArrayList<Article> searchArticle(ArrayList<Article> listArticles,
			String queryText) {
		queryText = queryText.toLowerCase();
		ArrayList<Article> results = new ArrayList<Article>();
		for (Article art : listArticles) {
			if (art.getTitle().toLowerCase().contains(queryText)) {
				results.add(art);
			}
		}
		return results;
	}

	@Override
	public boolean onClose() {
		Log.i(TAG, "onClose");
		return false;
	}
}
